# -*- coding: UTF-8 -*-
#auther:  xiang
# date:2017/06/26
#python 3.x

import urllib.request
import urllib.error
from bs4 import BeautifulSoup
import winxin02

class duanzi:
    def __init__(self):
        self.page_number = 1
        self.user_agent = 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)'
        self.headers = {'User-Agent' :self.user_agent}
        self.stories = []
        self.enable = False

    def getpage(self,page_number):
        try:
            url = "https://www.pengfu.com/xiaohua_%s.html"%(page_number)
            request = urllib.request.Request(url,headers=self.headers)
            response = urllib.request.urlopen(request)
            data = response.read().decode('utf-8')
            return data
        except urllib.error as e:
            if hasattr(e,"reason"):
                print("error",e.reason)
                return None

    def getpage_item(self,page_number):
        temp_duanzi=[]
        dict_value=[]
        data = self.getpage(page_number)
        if not data :
            print("捧腹网段子加载失败,请查看网络")
            return None
        soup = BeautifulSoup(data,"html.parser")
        txts = soup.find_all("dd")
        for txt in txts :
            div_br = txt.text
            div_br=div_br.split()
            dict_value.append(div_br)
        for Item in dict_value :
            temp=Item[3:]
            if len(temp) >1 :
                temp_duanzi.append(temp)
        return temp_duanzi

    def load_page(self):
        if self.enable==True:
            if len(self.stories)<2:
                temp_duanzi = self.getpage_item(self.page_number)
                if temp_duanzi:
                    self.stories.append(temp_duanzi)
                    self.page_number +=1


    def get_one(self,temp_duanzi,now_page):
        for i in range(len(temp_duanzi)):
            print("第%s页,第%s个段子\n%s\n"%(now_page,i+1,temp_duanzi[i]))
            self.load_page()
            user_choice = input("请选择功能:Enter|S|Q\n")
            if user_choice == 'S':
                self.enable = False
                txts=temp_duanzi[i]
                txts = str(txts).replace("("," ",1).replace(")"," ",1)
                return  winxin02.send_msg(txts)
            elif user_choice == 'Q':
                self.enable = False
                return

    def start(self):
        print("正在读取，Enter 查看 |S 发送微信好友 | Q退出")
        self.enable = True
        self.load_page()
        now_page = 0
        while self.enable:
            if len(self.stories)>0:
                temp_duanzi= self.stories[0]
                now_page +=1
                del self.stories[0]
                self.get_one(temp_duanzi,now_page)

if __name__ == '__main__':
    spider = duanzi()
    spider.start()
